
#include <libxml++/libxml++.h>
#include <libxml++/document.h>
#include <libxml++/keepblanks.h>
#include <string>
#include <unistd.h>
#include <iostream>

xmlpp::DomParser xml_doc;

void add_user(std::string user_name, std::string id)
{
    xmlpp::Document* doc = xml_doc.get_document();
    xmlpp::Node* node = doc->get_root_node();

    xmlpp::Element *elem = node->add_child("user");
    elem->set_attribute("name", user_name);
    elem->set_attribute("id", id);
    elem->set_attribute("level", "2");

    xmlpp::Element* nodeElement = dynamic_cast<xmlpp::Element*>(node);
    nodeElement->add_child_text("\n");

    doc->write_to_file_formatted("user_access.xml");
}

void remove_user(std::string id)
{
    xmlpp::Document* doc = xml_doc.get_document();
    xmlpp::Node* node = doc->get_root_node();

    const xmlpp::TextNode* nodeText;
    xmlpp::Node::NodeList node_list;
    xmlpp::Node::NodeList::iterator iter;

    xmlpp::Element* nodeElement = dynamic_cast<xmlpp::Element*>(node);
    nodeElement->add_child_text("\n");

    /* Get the "panels" and recurse through it's child. */
    node_list = node->get_children();
    for(iter = node_list.begin(); iter != node_list.end(); ++iter) {
        const xmlpp::Element* nodeElement = dynamic_cast<const xmlpp::Element*>(*iter);
        if(nodeElement) {
            const xmlpp::Attribute* attribute;
            attribute = nodeElement->get_attribute("id");
            if(attribute && attribute->get_value() == id) {
                node->remove_child(*iter);
            }
        }
    }

    doc->write_to_file_formatted("user_access.xml");
}

int main()
{
    const std::string xml_filepath = "user_access.xml";

    xml_doc.parse_file(xml_filepath);

    xml_doc.set_validate(); 
    add_user("Andrew", "2");
    add_user("Albinushka", "3");
    add_user("Har", "4");
    add_user("Har", "4");
    add_user("Har", "4");
    add_user("Har", "4");
    add_user("Har", "4");
    add_user("Har", "4");

    remove_user("4");

    return 0;
}
